package MainApplication;

import javax.mail.*;
import javax.mail.internet.*;

import java.util.*;

public class SendMail {
	private static final String SMTP_HOST_NAME = "smtp.mail.yahoo.com";
	private static final String SMTP_AUTH_USER = "danielmiu1988@yahoo.com";
	private static final String SMTP_AUTH_PWD  = "Numarul8!";

	private static final String emailSubjectTxt  = "[no-reply]Valoarea de prag a fost depasita";
	private static final String emailFromAddress = "danielmiu1988@yahoo.com";
	
	public SendMail(String emailTo, String threshold, boolean over) throws Exception{
		//Set the host smtp address
		Properties props = new Properties();
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		//props.put("mail.smtp.port", "465");
		//props.put("mail.smtp.socketFactory.port", "465");
		//props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		//props.put("mail.smtp.socketFactory.fallback", "false");

		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getDefaultInstance(props, auth);

		//create a message
		Message msg = new MimeMessage(session);
		
		// set the from and to address
	    InternetAddress addressFrom = new InternetAddress(emailFromAddress);
	    msg.setFrom(addressFrom);
	    
	    InternetAddress addressTo = new InternetAddress(emailTo);
	    msg.setRecipient(Message.RecipientType.TO, addressTo);
	    
	    msg.setSubject(emailSubjectTxt);
	    String message = "";
	    if (over)
	    	message = "Valoarea pentru " + threshold + " a depasit valoarea de prag! Verificati incinta urgent!";
	    else
	    	message = "Valoarea pentru " + threshold + " a coborat sub valoarea de prag! Verificati incinta urgent!";
	    
	    msg.setContent(message, "text/plain");
	    Transport.send(msg);
	     
	}

	private class SMTPAuthenticator extends javax.mail.Authenticator
	{

	    public PasswordAuthentication getPasswordAuthentication()
	    {
	        String username = SMTP_AUTH_USER;
	        String password = SMTP_AUTH_PWD;
	        return new PasswordAuthentication(username, password);
	    }
	}
}
